﻿<%@page contentType="text/html;charset=UTF-8" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<%@page import="java.text.NumberFormat" %>
<%@page import="be.destin.skos.core.SkosManager" %>
<%@page import="be.destin.skos.html.SkosHtmlManager" %>
<%@page import="be.destin.skos.html.LocalError" %>
<%@page import="be.destin.skos.core.SchemeInterface" %>
<%@page import="be.destin.skos.core.NotationScheme" %>
<%@page import="be.destin.skos.core.SchemeUsage" %>
<%@page import="be.destin.skos.core.ConceptScheme" %>
<%@page import="be.destin.skos.core.Term" %>
<%@page import="be.destin.skos.core.ReferringApplication" %>
<%@page import="be.destin.skos.core.Count" %>
<%@page import="be.destin.skos.core.Concept" %>
<%@page import="be.destin.skos.search.SkosSearch" %>
<%@page import="be.destin.skos.search.SearchResult" %>
<%@page import="be.destin.util.Util" %>
<%@page import="java.util.Collection" %>
<%@page import="java.util.ArrayList" %>
<%@page import="java.util.Map" %>
<%@page import="java.util.Map.Entry" %>
<%@page import="java.util.LinkedList" %>
<%@page import="java.util.TreeSet" %>
<%@page import="java.util.TreeMap" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%	 
   SkosHtmlManager skosHtmlManager = SkosHtmlManager.getAskosiSessionInstance(request);
   SkosManager skosManager = skosHtmlManager.getSkosManager();
   String language = skosHtmlManager.getLanguage();
   String submit = request.getParameter("submit");
   if (submit == null) submit = "EXPAND";
   String independant = request.getParameter("independant");
   String framing = request.getParameter("framed");
   boolean framed = framing != null && framing.equalsIgnoreCase("yes");
   if (independant != null && independant.equalsIgnoreCase("yes")) framed = false;
   String toexpand = request.getParameter("toexpand");
   if (toexpand == null) toexpand = "";
   LinkedList<String> sentences = null;
   			SchemeInterface aScheme = skosManager.openScheme ("thSubstances");
			LinkedList<SchemeInterface> schemes = new LinkedList<SchemeInterface>();
			schemes.add(aScheme);
   			aScheme = skosManager.openScheme ("thPlants");
			schemes.add(aScheme);
   			aScheme = skosManager.openScheme ("thAnimals");
			schemes.add(aScheme);
   			aScheme = skosManager.openScheme ("thMushrooms");
			schemes.add(aScheme);
%>
<html>
<head>
<title>Expand SKOS concepts references from a text, using concept schemes defined by <%=skosManager.getConfigDirectory()%></title>
<link rel="shortcut icon" href="image/tulipevertepetite.png" >
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/jqueryui.css" />
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/askosi.css" />
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/ajaxtags.css" />
	<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
    <script type="text/javascript" src="js/sessvars.js"></script>
    <script type="text/javascript" src="js/tablescroll.js"></script>
    <script type="text/javascript">
		sessvars.contextPath = "<%= request.getContextPath() %>";
		headerHeight=100;
		footerHeight=50;
	</script>
</head>
<body class="contentpage">
<% if (framed) {
%><script language="JavaScript">
parent.parent.parent.parent.focusFrame(this);
</script><%
} else {%><div id="header">
<a href="index.jsp" alt="All Concept Schemes"><img align="left" src="image/askosilogo.jpg" height="100" border="0"/></a>
<%String pageID = "TOC";%><%--@include file="basket.jnc"--%>
<div style="margin:8px 3px 3px 3px;"><form action="search.jsp" method="GET" class="searchForm"><input type="hidden" name="scheme" value=""/><%--
	   --%><label for="leftTruncation" alt="Left Truncation"><b>*</b><input type="checkbox" name="leftTruncation" value="on" checked/></label><input type="text" name="query" size="30"/><b>*</b>&nbsp;<%--
   	   --%><label for="byPieces" alt="By Pieces"><b>by pieces:</b><input type="checkbox" name="byPieces" value="on"/></label><%--
	   --%><input type="image" src="image/search.png" name="Search" alt="Search"><%--
	--%></form></div>
  </div>
<%
}%>

<%if(!framed){%>
<div id="footer"><p style="margin:6px; padding:2px;"><span class="ToC">
 <a href="index.jsp?sort=alfa">Alphabetical</a>
 or <a href="index.jsp">Most Used Schemes <strong>Table of Content</strong></a>
as a <a href="index.jsp?profile=guest">guest</a> or as a <a href="index.jsp?profile=BIBLIO">BIBLIO</a></span>
<span class="ToC">
 <a href="analyze.jsp">Analyze</a>
</span>
</p><p style="margin:4px">Thesaurus navigation and maintenance, Indexation browsing are services developed in the <a href="http://www.askosi.org">ASKOSI</a> project.</p>
</div>
<%}%>

<div id="content">
<img src="image/carrevide.gif" height="100" border="0" alt="top margin"/><br style="clear:both"/>

<form method="POST" action="analyze.jsp">
<textarea name="toexpand" rows=20 cols=100><%=(submit.equals("EXPAND")?skosManager.toStringScheme_Concept(toexpand,language,null,null,null,true):toexpand)%></textarea>
<p><input type="submit" name="submit" value="ANALYZE"/> <input type="submit" name="submit" value="FORMULATE"/> <input type="submit" name="submit" value="CAS"/> <input type="submit" name="submit" value="EXPAND"/></p>
</form>
<%if(submit.equals("FORMULATE")||submit.equals("CAS")) {
   sentences = new LinkedList<String>();
   if(submit.equals("FORMULATE")) {
	String[]sss = toexpand.split(",|\n|[.] |[;!?]| [(]");
	for (String ssss: sss) { sentences.add(ssss); }
   } else {
    //REMOVE EINECS!!!
    toexpand = toexpand.replaceAll("[245][0-9][0-9][-][0-9][0-9][0-9][-][0-9][^0-9]","");
    String forSplit = "§!"+toexpand.replaceAll("([0-9]+[-][0-9]+[-][0-9]+)","§$1§!");
	String[]sss = forSplit.split("§");
	for (String ssss: sss) { 
		ssss = ssss.trim();
		if (ssss.trim().length() > 0 && ssss.charAt(0) != '!') {
			sentences.add(ssss);
		}
	}
   }
%><%--=sentences--%>
<form method="POST" action="clipboard.jsp" target="clipboard">
<table border="0" cellspacing="1">
<tr style="background:#AAF"><th>Label</th><th>Thesaurus</th><th>CAS</th><th>min</th><th>MAX</th><th>unit</th><th>SAQ</th><th>Biblio</th></tr>
<%  TreeMap<String,Integer> counts = new TreeMap<String,Integer>(); 
    int group = 0;
	boolean odd = false;
    for (String sentence : sentences) {
		group++;
		odd = !odd;
		String rowStyle = "background-color:#ddd";
		if (odd) { rowStyle = ""; }
		boolean first = true;
		Collection<SearchResult> result;
		if(submit.equals("FORMULATE")) {
			result = SkosSearch.analyzeSentence(skosHtmlManager,true,schemes,sentence);
		} else { // CAS
			result = new ArrayList<SearchResult>();
			SchemeInterface casScheme = skosManager.openScheme ("thSubstances");
			if (casScheme != null && casScheme instanceof ConceptScheme) {
				Concept aConcept = casScheme.getNotationConcept("CAS",sentence);
				SearchResult toAdd;
				if (aConcept != null) {
					toAdd = new SearchResult(aConcept.getPrefLabel("en",false),null,null,null,aConcept.getScheme_About(),1.0f);
					result.add(toAdd);
				}
			}
		}
		if (result == null || result.isEmpty()) {
			%><tr style="<%=rowStyle%>"><td style="text-align:left"><%=sentence%></td><td valign="top" style="text-align:left;background:#F00"><input type="text" size="50"></td><td style="text-align:left;background:#F00"><input type="text" size="13"></td><td><input type="text" size="6"></td><td><input type="text" size="6"></td><td><input type="radio">mL/L <input type="radio">mg/kg</td><td></td><td></td></tr><%
		} else {
		SearchResult bestResult = null;
		LinkedList<SearchResult> kept = new LinkedList<SearchResult>();
		for (SearchResult aTri: result) {
			if (aTri.getQuality() >= 1.0f) {
				kept.add(aTri);
			}
		}
		if (kept.size() >= 1) {
		  for (SearchResult aTri: kept) {
			%><tr style="<%=rowStyle%>"><%
			if (first) {
			%><td style="text-align:left" rowspan="<%=kept.size()%>"><%=sentence%></td><%
			}
			%><td valign="top"style="text-align:left;background:#8F4"><%
			if (kept.size() > 1) {
				%><input type="radio" name="<%=group%>" value="<%=aTri.getAbout()%>"/><%
			}
			String synonym = aTri.getSynonym();
			if (synonym == null || synonym.isEmpty()) synonym = "";
			else synonym = synonym + " ==&gt; ";
			Concept aConcept = skosManager.getScheme_Concept(aTri.getAbout());
				String aCAS = "";
				String saq = "";
				String biblio = "";
				String label = aTri.getLabel();
				if (aConcept != null) {
					aCAS = aConcept.getNotation("CAS");
					if (aCAS == null) aCAS = "";
					else aCAS = aCAS.replace("_","-");
					ReferringApplication ra = aConcept.getApplicationUsage("SAQ");
					if (ra != null) {
						Count nora = ra.getCount("page");
						if (nora != null) {
							saq = aConcept.toHtmlCount(skosHtmlManager, "SAQ", nora,true);
						}
					}
					ra = aConcept.getApplicationUsage("bibl");
					if (ra != null) {
						Count nora = ra.getCount("keyword");
						if (nora != null) {
							biblio = aConcept.toHtmlCount(skosHtmlManager, "bibl", nora,true);
						}
					}
					label = aConcept.toHtmlLabel(skosHtmlManager,false);
				}
			%><%=synonym%><%=label%></td><td style="text-align:left;background:#8F4"><%=aCAS%></td><%
			if (first) {
			%><td rowspan="<%=kept.size()%>"><input type="text" size="6"></td><td rowspan="<%=kept.size()%>"><input type="text" size="6"></td><td rowspan="<%=kept.size()%>"><input type="radio" value="v" name="u<%=aTri.getAbout()%>">mL/L <input type="radio" value="v" name="u<%=aTri.getAbout()%>">mg/kg</td><%
			}%><td><%=saq%></td><td><%=biblio%></td></tr><%
		    first = false;
		  }
		} else {
			%><tr style="<%=rowStyle%>"><%
			for (SearchResult aTri: result) {
				if (first) {
				%><td style="text-align:left" rowspan="<%=result.size()+1%>"><%=sentence%></td><%
				}
				%><td valign="top"style="text-align:left;background:#FF6"><%
				if (result.size() > 1) {
					%><input type="radio" name="<%=group%>" value="<%=aTri.getAbout()%>"/><%
				}
				Concept aConcept = skosManager.getScheme_Concept(aTri.getAbout());
				String aCAS = "";
				String saq = "";
				String biblio = "";
				String label = aTri.getLabel();
				if (aConcept != null) {
					aCAS = aConcept.getNotation("CAS");
					if (aCAS == null) aCAS = "";
					else aCAS = aCAS.replace("_","-");
					saq = aConcept.toHtmlConceptUsage(skosHtmlManager, "SAQ", true);
					ReferringApplication ra = aConcept.getApplicationUsage("SAQ");
					if (ra != null) {
						Count nora = ra.getCount("page");
						if (nora != null) {
							saq = aConcept.toHtmlCount(skosHtmlManager, "SAQ", nora,true);
						}
					}
					ra = aConcept.getApplicationUsage("bibl");
					if (ra != null) {
						Count nora = ra.getCount("keyword");
						if (nora != null) {
							biblio = aConcept.toHtmlCount(skosHtmlManager, "bibl", nora,true);
						}
					}
					label = aConcept.toHtmlLabel(skosHtmlManager,false);
				}
				String synonym = aTri.getSynonym();
				if (synonym == null || synonym.isEmpty()) synonym = "";
				else synonym = synonym + " ==&gt; ";
				%><img src="/askosi/image/level<%=Float.toString(aTri.getQuality()+0.05f).substring(2,3)%>.png" border="0"/> <%=synonym%><%=label%></td><td style="text-align:left;background:#FF6"><%=aCAS%></td><%
				if (first) {
				%><td rowspan="<%=result.size()+1%>"><input type="text" size="6"></td><td rowspan="<%=result.size()+1%>"><input type="text" size="6"></td><td rowspan="<%=result.size()+1%>"><input type="radio">mL/L <input type="radio">mg/kg</td><%
				}%><td><%=saq%></td><td><%=biblio%></td></tr><%
				first = false;
			}
			%><tr style="<%=rowStyle%>"><td valign="top"style="text-align:left;background:#FF6"><%
				if (result.size() > 1) {
					%><input type="radio" name="<%=group%>" value="OTHER"/><%
				}
			%><input type="text" size="50"></td><td style="text-align:left;background:#FF6"><input type="text" size="13"></td><td></td><td></td></tr><%
		}
		}
	}
%></table>
<p><input type="submit" name="submit" value="VALIDATE"/> <input type="submit" name="submit" value="STORE"/></p>
<%} else if(submit.equals("ANALYZE")) {
   sentences = Util.sentenceSplitter(toexpand);
%>
<form method="POST" action="clipboard.jsp" target="clipboard">
<%  TreeMap<String,Integer> counts = new TreeMap<String,Integer>(); 
    for (String sentence : sentences) {
		Collection<SearchResult> result = SkosSearch.analyzeSentence(skosHtmlManager,true,schemes,sentence);
		String prev="";
		String prevKey="";
		for (SearchResult aTri: result) {
			String key = aTri.getAbout();
			if (!prev.isEmpty() && aTri.getLabel().startsWith(prev)) {
				counts.put(prevKey,counts.get(prevKey)-1);
			}
			if (counts.containsKey(key)) {
				counts.put(key,counts.get(key)+1);
			} else {
				counts.put(key,1);
			}
			prev = aTri.getLabel();
			prevKey = key;
		}
	}
%><table><%
	int p = 0;
    TreeMap<Integer,String> descending = new TreeMap<Integer,String>(); 
    for (Entry anEntry : counts.entrySet() ) {
	     String key = anEntry.getKey().toString();
		 int value = (Integer)anEntry.getValue();
		 if (value > 0) descending.put(1000000000-(value*100000)+p, key);
		 p++;
	}
    for (Entry anEntry : descending.entrySet() ) {
	     String key = anEntry.getValue().toString();
		 %><%--int poscode = key.indexOf('\t');
		 int pNote = key.indexOf(':');
		 if (pNote < 0) pNote = poscode;
		 %><tr><td><input type="checkbox" name="<%=key.substring(poscode+1)%>"/></td><th><%=(1000000000-(Integer)anEntry.getKey())/100000+1%></th><td style="text-align:left"><%=key.substring(poscode+1)%></td><td style="text-align:left"><%=key.substring(0,pNote)%><%=key%></td><td style="text-align:left"><%=key.substring(pNote,poscode)%></td></tr><% --%><%
         Concept bConcept = skosManager.getScheme_Concept(key);		 
		 %><tr><td><input type="checkbox" name="<%=key%>"/></td><th><%=(1000000000-(Integer)anEntry.getKey())/100000+1%></th><td style="text-align:left"><%=key%></td><td style="text-align:left"><%=bConcept.getPrefLabel(language,false)%></td><td style="text-align:left"></td></tr><%
	}
%></table><input type="submit" name="submit" value="CLIPBOARD"/>
<p><%=descending.entrySet().size()%> concepts found / <%=sentences.size()%> sentences.</p>
</form>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<%}
%>
